import mox from './mox-weapp/index.js';
import RTLog from './modules/rt_log.js';
import Util from './modules/util.js';
import Config from './modules/config.js';
import RequestCache from './mox-weapp/request_cache.js';
import Modules from './modules/index.js';
import { filterNotFocusAccounts } from './modules/filter_account';

App({
    $modules: Modules,
    mox: mox,
    globalData: {
        themeColor: '#ffb146',
        cfgData: {},
        productInfo: {}, // 对应题目列表
        answers: [],
        testTitle: '',
        accountInfo: '',
        notFocusAccounts: {}
    },
    onLaunch() {
        console.log(
            '%c%s',
            'color: yellow;',
            `appName：${'阔爱大孔农'}、appId：${'wx999703fd265c7cb2'}、mpid：${'zhidamp00'}、env：${'release'}`
        );
        let t0 = Date.now();
        mox.init(true);
        mox.theme.login = {
            logo: 'https://qncdn.mopic.mozigu.net/f/mr6kod18k32ah1s63tg/12641938cfae/logo-2.png' // 规范：248x248
        };
        mox.request.setHost(Config.host['release']);

        if ('release' != 'release') {
            wx.setNavigationBarTitle({
                title: '阔爱大孔农-release'
            });
        }
        mox.login({
            success: (res) => {
                console.log('login_user-----------', res);
                mox.stat('__visit__', (Date.now() - t0) / 1000.0);
                filterNotFocusAccounts().then((res) => {
                    this.globalData.notFocusAccounts = res;
                });
            },
            fail: (err) => {
                mox.stat(`mox_init fail:${err.msg || err.errMsg || '未知错误'}`);
            }
        });
        this.checkUpdate();
    },
    checkUpdate() {
        const updateManager = wx.getUpdateManager();
        // 监听请求更新结果
        updateManager.onCheckForUpdate((res) => {
            // false && res;
            // console.log(res.hasUpdate)
        });
        updateManager.onUpdateReady(() => {
            // 新的版本已经下载好
            wx.showModal({
                title: '更新提示',
                showCancel: false,
                content: '新版本已经准备好，请重启应用',
                success: (res) => {
                    if (res.confirm) {
                        // 调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate();
                    }
                }
            });
        });
        updateManager.onUpdateFailed(() => {
            // 新的版本下载失败
            wx.showModal({
                title: '更新提示',
                content: '新版本下载失败',
                showCancel: true,
                confirmText: '重试',
                success: (res) => {
                    if (res.confirm) {
                        // 调用 applyUpdate 应用新版本并重启
                        this.checkUpdate();
                    }
                }
            });
        });
    },
    downloadAndUpdate: function (updateManager) {
        wx.showLoading();
        updateManager.onUpdateReady(function () {
            wx.hideLoading();
            updateManager.applyUpdate();
        });
        updateManager.onUpdateFailed(function () {
            wx.hideLoading();
        });
    },
    onError(msg) {
        try {
            msg = Util.errorMessageReadable(msg);
            const skiped_errors = [
                /:toast can't be found$/,
                /.*showLoading.*/,
                /.*updateTextView:fail.*/,
                /.*insertTextView:fail.*/,
                /.*insertImageView:fail.*/,
                /.*updateImageView:fail.*/,
                /.*removeTextView:fail.*/,
                /.*removeImageView:fail.*/,
                /.*no advertisement*/,
                /.*updateVideoPlayer:fail invalid videoPlayerId*/,
                /.*removeVideoPlayer:fail.*/,
                /.*getUserProfile:fail.*/,
                /.*operateVideoPlayer:fail.*/,
                /.*requestPayment:fail.*/,
                /.*requestPayment:fail cancel*/,
                /.*navigateBack:fail.*/,
                /.*navigateBack:fail no page*/,
                /.*未知错误.*/,
                /.*insertVideoPlayer:fail.*/,
                /.*operateWXDataForAd:fail.*/,
                /.*jsapi has no permission*/,
                /.*network interrupted error*/,
                /.*"errno":5,"errMsg":"request:fail timeout"*/,
                /.*request:fail -7:net::ERR_TIMED_OUT*/
            ];

            for (let i = 0; i < skiped_errors.length; ++i) {
                if (skiped_errors[i].test(msg)) {
                    return;
                }
            }
            RTLog.error('onError:' + msg);
            mox.stat('onError fail');
        } catch (e) {
            console.error('exception when onError:', e);
        }
    },
    onUnhandledRejection(evt) {
        this.onError(
            evt && evt.reason ? evt.reason.message || evt.reason.errMsg : 'UnhandledRejection Error'
        );
    },
    onHide() {
        RequestCache && RequestCache.clearExpiredData();
    }
});

// 格式化日期：yyyy-MM-dd hh:mm:ss
Date.prototype.format = function (fmt) {
    var o = {
        'M+': this.getMonth() + 1, //月份
        'd+': this.getDate(), //日
        'h+': this.getHours(), //小时
        'm+': this.getMinutes(), //分
        's+': this.getSeconds(), //秒
        'q+': Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
            );
        }
    }

    return fmt;
};
